<template>
  <div class="detectionReferenceEdit detailView">
    <Modal v-model="isView"
           :mask-closable="false"
           title="编辑检测指标"
           :footer-hide="true"
           width="60%">
      <Form :model="item"
            label-position="right"
            :label-width="100"
            :rules="rules"
            ref="item">
        <FormItem label="名称"
                  prop="name">
          <el-input v-model="item.name"
                    clearable
                    placeholder="请输入名称"/>
        </FormItem>
        <FormItem label="code"
                  prop="code">
          <el-input v-model="item.code"
                    placeholder="请输入code"
                    clearable
                    v-if="!item.id"/>
          <el-input v-model="item.code"
                    v-else
                    disabled
                    clearable
                    placeholder="请输入code"/>
        </FormItem>
        <FormItem label="图标">
          <el-upload :action="fileLogoUploadAction"
                     class="avatar-uploader"
                     :show-file-list="false"
                     accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                     :before-upload="beforeAvatarUpload"
                     :on-success="uploadLogoSuccess">
            <img v-if="item.imageUrl" :src="item.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </FormItem>
        <FormItem label="单位"
                  prop="unit">
          <el-input v-model="item.unit"
                    clearable
                    placeholder="请输入单位"/>
        </FormItem>
        <FormItem label="内容">
          <el-input v-model="item.content"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入内容"/>
        </FormItem>

        <FormItem label="通过公式计算">
          <el-radio-group v-model="item.isFormula">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </FormItem>
        <FormItem label="指标参数" v-if="item.isFormula===1" prop="params">
          <el-select v-model="item.params"
                     filterable
                     remote
                     clearable
                     multiple
                     reserve-keyword
                     placeholder="请输入检测项"
                     :remote-method="searchMethod"
                     :loading="loading"
                     class="w-400">
            <el-option v-for="item in optionsFilterList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.code">
            </el-option>
          </el-select>

        </FormItem>
        <FormItem label="参数" v-if="item.isFormula===1">
          <el-checkbox-group v-model="item.paramsExtra">
            <el-checkbox label="sex">性别</el-checkbox>
            <el-checkbox label="age">年龄</el-checkbox>
          </el-checkbox-group>
        </FormItem>

        <FormItem label="公式" v-if="item.isFormula===1" prop="formula">
          <el-input v-model="item.formula"
                    type="textarea"
                    autosize
                    placeholder="请输入公式"/>
        </FormItem>

        <FormItem label="结果判断">
          <el-button type="primary"
                     @click="handleAdd">添 加
          </el-button>
          <Table :columns="tableCol"
                 :data="tableData"
                 class="mt-20"
                 border>
            <template slot-scope="{row,index}"
                      slot="action">
              <span @click="handleDel(row)">删除</span>
            </template>
            <template slot-scope="{row,index}"
                      slot="ending">
              <Select v-model="row.status"
                      class="w-200"
                      placeholder="请选择">
                <Option v-for="item in stateDataSource"
                        :value="item.status"
                        :key="item.status">{{ item.name }}
                </Option>
              </Select>

              <!--              <p  v-if="row.status===1">正常</p>-->
<!--              <p  v-if="row.status===0">异常</p>-->
            </template>
          </Table>
        </FormItem>
        <FormItem label="临床意义">
          <div>
            <vue-neditor-wrap :destroy="true"
                              v-model="item.clinicalSignificance"
                              :config="myConfig"></vue-neditor-wrap>
          </div>
        </FormItem>

      </Form>
      <div class="operationView">
        <el-button type="primary"
                   @click="handleCancel">取 消
        </el-button>
        <el-button type="primary"
                   @click="handleSave('item')">保 存
        </el-button>
      </div>
    </Modal>
    <Modal v-model="isShow"
           :mask-closable="false"
           title="编辑指标范围"
           :footer-hide="true"
           width="700px">
      <Form :model="editModel"
            label-position="right"
            :label-width="100"
            ref="form">
        <FormItem label="范围"
                  prop="range">
          <div>
            <el-row>
              <el-col :span="12">
                <el-input v-model="editModel.value_1"
                          clearable
                          placeholder="请输入范围"
                          class="w-200"/>
              </el-col>
              <el-col :span="12">
                <Select v-model="editModel.relationship1"
                        clearable
                        placeholder="请选择关系"
                        class="w-200">
                  <Option v-for="item in relations_1"
                          :value="item.value"
                          :key="item.value">{{ item.label }}
                  </Option>
                </Select>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-input v-model="editModel.value_2"
                          clearable
                          class="w-200"
                          placeholder="请输入范围"/>
              </el-col>
              <el-col :span="12">
                <Select v-model="editModel.relationship2"
                        clearable
                        placeholder="请选择关系"
                        class="w-200">
                  <Option v-for="item in relations_2"
                          :value="item.value"
                          :key="item.value">{{ item.label }}
                  </Option>
                </Select>
              </el-col>
            </el-row>
          </div>
        </FormItem>
        <FormItem label="选项"
                  prop="result">
          <div>
            <el-row>
              <el-col :span="12">
                <Select v-model="editModel.type"
                        clearable
                        class="w-200"
                        placeholder="请选择"
                        @on-change="initValueList">
                  <Option v-for="item in typeList"
                          :value="item.value"
                          :key="item.value">{{ item.label }}
                  </Option>
                </Select>
              </el-col>
              <el-col :span="12">
                <Select v-model="editModel.typeValue"
                        clearable
                        class="w-200">
                  <Option v-for="item in valueList"
                          :value="item.value"
                          :key="item.value">{{ item.label }}
                  </Option>
                </Select>
              </el-col>
            </el-row>
          </div>
        </FormItem>
        <FormItem label="状态">
          <Select v-model="editModel.status"
                  clearable
                  class="w-200"
                  placeholder="请选择">
            <Option v-for="item in stateDataSource"
                    :value="item.status"
                    :key="item.status">{{ item.name }}
            </Option>
          </Select>

        </FormItem>
        <FormItem label="结果"
                  prop="result">
          <el-input v-model="editModel.result"
                    clearable
                    placeholder="请输入结果"
                    type="text"/>
        </FormItem>
      </Form>
      <div class="operationView">
        <el-button type="primary"
                   @click="closeModal">取 消
        </el-button>
        <el-button type="primary"
                   @click="addItem">保 存
        </el-button>
      </div>
    </Modal>
  </div>
</template>

<script>
import LabelWrap from "element-ui/packages/form/src/label-wrap";
import VueNeditorWrap from "vue-neditor-wrap";

export default {
  name: "detectionReferenceEdit",
  data() {
    return {
      isView: false,
      isShow: false,
      loading: false,
      optionsFilterList: [],
      myConfig: {
        // 你的UEditor资源存放的路径,相对于打包后的index.html
        UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: '418',
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 关闭自动保存
        enableAutoSave: false,
        scaleEnabled: true
      },
      stateDataSource: [
        {
          status: 0,
          name: '异常'
        },
        {
          status: 1,
          name: '正常'
        }
      ],
      item: {
        id: 0,
        name: '',
        code: '',
        content: '',
        criterion: '',
        remark: '',

        imageUrl: '',
        isFormula: 0,
        params: [],
        paramsExtra: [],
        formula: '',
        clinicalSignificance: '',
      },
      relations_1: [
        {
          value: '<',
          label: '大于'
        },
        {
          value: '<=',
          label: '大于等于'
        }
      ],
      relations_2: [
        {
          value: '<',
          label: '小于'
        },
        {
          value: '<=',
          label: '小于等于'
        },
        {
          value: '=',
          label: '等于'
        },
      ],
      typeList: [
        {
          value: 'sex',
          label: '性别'
        },
        {
          value: 'age',
          label: '年龄'
        },
        {
          value: 'bloodSugar',
          label: '血糖'
        }
      ],
      valueList: [],
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入code', trigger: 'blur'}
        ],
        params: [
          {required: true, type: 'array', message: '请选择检测项', trigger: 'blur'}
        ],
        formula: [
          {required: true, message: '请输入公式', trigger: 'blur'}
        ],
      },
      tableCol: [
        {
          title: '范围',
          key: 'range'
        },
        {
          title: '结果',
          key: 'result'
        },
        {
          title: '状态',
          slot: 'ending'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }
      ],
      tableData: [],
      editModel: {
        range: "",
        result: "",
        relationship1: "",
        relationship2: "",
        value_1: "",
        value_2: "",
        type: "",
        typeValue: "",
        status: ''
      },
      fileLogoUploadAction: this.api.file.upload,
    }
  },
  methods: {
    openView(row) {
      this.isView = true;
      this.tableData = [];
      this.item = {
        id: 0,
        name: '',
        code: '',
        content: '',
        criterion: '',
        remark: '',
        imageUrl: '',
        isFormula: 0,
        params: [],
        paramsExtra: [],
        formula: '',
        clinicalSignificance:''
      }
      if (row) {
        this.getAllFieldCNName()
        this.item = Object.assign(this.item, row);
        let criterion = this.item.criterion;
        if (criterion) {
          this.tableData = JSON.parse(criterion);
        } else {
          this.tableData = [];
        }
      }
    },
    handleCancel() {
      this.isView = false;
      this.$refs['form'].resetFields();
    },
    initValueList(obj) {
      if ("sex" == this.editModel.type) {
        this.valueList = [{
          value: 1,
          label: '男'
        },
          {
            value: 0,
            label: '女'
          }];
      } else if ("age" == this.editModel.type) {
        this.valueList = [];
      } else if ("bloodSugar" == this.editModel.type) {
        this.valueList = [{
          value: 0,
          label: '凌晨'
        },
          {
            value: 2,
            label: '早餐后1H'
          },
          {
            value: 3,
            label: '早餐后2H'
          },
          {
            value: 4,
            label: '午餐前'
          },
          {
            value: 5,
            label: '午餐后1H'
          },
          {
            value: 6,
            label: '午餐后2H'
          },
          {
            value: 7,
            label: '晚餐前'
          },
          {
            value: 8,
            label: '晚餐后1H'
          },
          {
            value: 9,
            label: '晚餐后2H'
          },
          {
            value: 10,
            label: '睡前'
          },
          {
            value: 11,
            label: '空腹'
          },
          {
            value: 12,
            label: '餐后1小时'
          },
          {
            value: 13,
            label: '餐后2小时'
          },
          {
            value: 99,
            label: '随机血糖'
          }];
      }
    },
    closeModal() {
      this.isShow = false;
    },
    addItem() {
      let range_1 = "";
      if (this.editModel.value_1) {
        if (!this.editModel.relationship1) {
          this.$Message.error("请配置关系");
          return;
        }
        range_1 = this.editModel.value_1 + this.editModel.relationship1;
      }
      let range_2 = "";
      if (this.editModel.value_2) {
        if (!this.editModel.relationship2) {
          this.$Message.error("请配置关系");
          return;
        }
        range_2 += this.editModel.relationship2 + this.editModel.value_2;
      }
      let range = "";
      if (!range_1 && !range_2) {
        this.$Message.error("请配置范围值");
        return;
      }
      if (range_1) {
        range += range_1;
      }
      range += "value";
      if (range_2) {
        range += range_2;
      }
      let model = {
        range: range,
        result: this.editModel.result,
        type: this.editModel.type,
        typeValue: this.editModel.typeValue,
        status: this.editModel.status
      };
      this.tableData.push(model);
      this.closeModal();
    },
    handleAdd() {
      this.editModel = {
        range: "",
        result: "",
        relationship1: "",
        relationship2: "",
        value1: "",
        value2: "",
        status: ''
      };
      this.isShow = true;
    },
    handleDel(row) {
      this.tableData.splice(row._index, 1);
    },
    handleSave(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let obj = Object.assign({}, this.item);
          obj.criterion = JSON.stringify(this.tableData);
          this.post(this.api.detectionReferenceEdit.url, obj).then((res) => {
            if (res.data.code === '200') {
              this.$message.success('保存成功！');
              this.handleCancel();
              this.$emit('getList')
            }
          });
        }
      })
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    uploadLogoSuccess(res) {
      this.$set(this.item, 'imageUrl', res.object[0])
    },
    //查询所有检测项
    getAllFieldCNName() {
      this.post(this.api.getAllFieldCNName).then((res) => {
        if (res.data.code === '200') {
          this.optionsFilterList = res.data.object
        }
      })
    },
    searchMethod(query) {
      if (query !== '') {
        let _this = this;
        _this.loading = true; // 锁住
        this.post(this.api.detectionReferenceList.url, {
          name: query,
          pageIndex: 0,
          pageSize: 10
        }).then(res => {
          if (res.data.code === '200') {
            _this.loading = false;
            _this.optionsFilterList = res.data.object;
          }
        })
      } else {
        this.optionsFilterList = [];
      }
    }
  },

  components: {LabelWrap,VueNeditorWrap}
}
</script>

<style scoped>

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 15px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}

.avatar {
  width: 160px;
  height: 160px;
  display: block;
}
</style>
